package cn.com.hhrcw.enterprise.web;

import cn.com.hhrcw.enterprise.params.OpBatchParams;
import cn.com.hhrcw.enterprise.vo.OpBatchVO;
import cn.com.hhrcw.entity.OpBatch;
import cn.com.hhrcw.entity.OpJob;
import cn.com.hhrcw.entity.SysUserDepart;
import cn.com.hhrcw.mapstruct.EnOpBatchConvert;
import cn.com.hhrcw.service.IOpBatchService;
import cn.com.hhrcw.service.IOpJobService;
import cn.com.hhrcw.service.ISysUserDepartService;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.function.Function;

/**
 * 职位批次
 *
 * @author jiangdong
 * @since 2020-10-29
 */
@RestController
@Slf4j
@RequestMapping("/en/opBatch")
@Api(tags = "职位_批次")
@Validated
public class EnOpBatchController extends JeecgController<OpBatch, IOpBatchService> {

    @Autowired
    private IOpBatchService opBatchService;

    @Autowired
    private IOpJobService opJobService;

    @Autowired
    private EnOpBatchConvert enOpBatchConvert;

    @Autowired
    private ISysUserDepartService userDepartService;

    /**
     * 分页列表查询
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<OpBatchVO>> list(OpBatchParams params, HttpServletRequest request) {
        QueryWrapper<OpBatch> queryWrapper = QueryGenerator.initQueryWrapper(enOpBatchConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUserDepart userDepart = userDepartService.lambdaQuery().eq(SysUserDepart::getUserId, sysUser.getId()).one();
        queryWrapper.eq("company_id", userDepart.getDepId());

        IPage<OpBatch> page = opBatchService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<OpBatch, OpBatchVO> fun = opBatch -> enOpBatchConvert.toVO(opBatch);

        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<OpBatchVO> queryById(String id) {
        OpBatch opBatch = opBatchService.lambdaQuery().eq(OpBatch::getId, id).eq(OpBatch::getDelFlag, false).one();
        if (opBatch == null) {
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(enOpBatchConvert.toVO(opBatch));
    }

    /**
     * 批次-新建批次
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog(logType = 2, ty = "insert", value = "职位批次添加")
    @ApiOperation(value = "添加", notes = "添加")
    @RequiresPermissions("opBatch:add")
    public Result<?> add(@RequestBody @Valid OpBatchParams params) {
        LambdaQueryWrapper<OpJob> jobQuery = new LambdaQueryWrapper<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUserDepart userDepart = userDepartService.lambdaQuery().eq(SysUserDepart::getUserId, sysUser.getId()).one();
        OpBatch opBatch = enOpBatchConvert.toEntity(params);
        opBatch.setCreateBy(sysUser.getId());
        opBatch.setCreateTime(DateUtil.date());
        opBatch.setDelFlag(false);
        opBatch.setCompanyId(userDepart.getDepId());
        boolean saved = opBatchService.save(opBatch);
        return saved ? Result.ok(opBatch.getId()) : Result.error("添加失败");
    }

    /**
     * 批次-修改批次
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog(logType = 2, ty = "visit", value = "职位批次编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("opBatch:edit")
    public Result<?> edit(@RequestBody @Valid OpBatchParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OpBatch opBatch = enOpBatchConvert.toEntity(params);
        opBatch.setUpdateBy(sysUser.getId());
        opBatch.setUpdateTime(DateUtil.date());

        boolean updated = opBatchService.updateById(opBatch);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog(logType = 2, ty = "visit", value = "职位批次删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("opBatch:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer opJobCount = opJobService.lambdaQuery().eq(OpJob::getDelFlag, false).in(OpJob::getBsId, id).eq(OpJob::getBsType, 0).count();
        if (opJobCount > 0) {
            return Result.error("批次下还有职位，删除失败");
        }

        LambdaUpdateWrapper<OpBatch> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(OpBatch::getId, id).set(OpBatch::getDelFlag, true).set(OpBatch::getUpdateBy, sysUser.getUsername()).set(OpBatch::getUpdateTime, DateUtil.date());

        boolean deleted = opBatchService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, OpBatchParams params) {
        OpBatch opBatch = enOpBatchConvert.toEntity(params);
        opBatch.setDelFlag(false);
        QueryWrapper<OpBatch> queryWrapper = QueryGenerator.initQueryWrapper(opBatch, request.getParameterMap());
        List<OpBatch> data = opBatchService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("职位_批次", "职位_批次");
        String url = super.exportXls(exportParams, OpBatchVO.class, enOpBatchConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OpBatch.class);
    }

}
